# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Node, NodeList, Template, Context, resolve_variable
from django.template import get_library, Library, InvalidTemplateLibrary, TemplateSyntaxError
from django.template.loader import get_template
from django.db.models import get_model

register = Library()

class TreeListNode(Node):
    def __init__(self, model, template_path, wraptag, verbose):
        self.__model = get_model(*model.split('.'))
        self.__template = get_template(template_path)
        self.__wraptags = ('<%s class="section">' % wraptag, '</%s>' % wraptag)
        self.__verbose = verbose
          
    def render(self, context):
        nodes = NodeList()
        related_content = self.__model.objects.all()
        context['verbose'] = self.__verbose
        
        def _get_childs(parent):
            nodes.append(self.__wraptags[0])
            if parent.parent == parent:
                for node in self.__template:
                    nodes.append(node.render(context))
            
            for child in parent.subsections.order_by('order'):
                context['content'] = child
                for node in self.__template:
                    nodes.append(node.render(context))
                _get_childs(child)
            nodes.append(self.__wraptags[1])
            return 
      
        for content in related_content:
            if not content.parent_id:
                context['content'] = content
                for node in self.__template:
                    nodes.append(node.render(context))
                _get_childs(content)
                
        return nodes.render(context)
    
def get_list(parser, token):
    """
        example tags:
        {% get_list of "sections" using "template_name" wrapped_by "ul" verbose %}
        {% get_list of "categories" wrapped_by "div" %}
    """
    # estrazione parametri
    params = token.contents.split()

    # parametri di default
    verbose = False
    wraptag = "ul"
    default_wrappers = ["ul", "ol", "div", "p"]
    
    if not (len(params)%2): 
        if not "verbose" in params:
            raise TemplateSyntaxError, "il numero di argomenti in %r non e' corretto" % params[0]
        else:
            verbose = True
        
    if "of" in params:
        model = "%s" % params[params.index("of")+1][1:-1]
            
    if "using" in params:
        template = "%s.html" % params[params.index("using")+1][1:-1]
    
    if "wrapped_by" in params:
        if params[params.index("wrapped_by")+1][1:-1] in default_wrappers:
            wraptag = params[params.index("wrapped_by")+1][1:-1]
    
    return TreeListNode(model, template, wraptag, verbose)
get_list = register.tag(get_list)

@register.filter
def booleanIcon(value):
    if value:
        try:
            from django.utils.safestring import mark_safe
            return mark_safe("<img src=\"/media/admin/yes.png\" alt=\"yes\" />")
        except:
            return "<img src=\"/media/admin/yes.png\" alt=\"yes\" />"
    else:
        try:
            from django.utils.safestring import mark_safe
            return mark_safe("<img src=\"/media/admin/no.png\" alt=\"no\" />")
        except:
            return "<img src=\"/media/admin/no.png\" alt=\"no\" />"

